let n = 3

var generateMatrix = function (n) {
    let arr = Array.from({ length: n }, () => Array(n).fill(0)); // 初始化二维数组
    let x = 0, y = 0;
    let count = 1, offset = 0;
    let cishu = Math.floor(n / 2);

    while (cishu) {
        // 从左到右填充
        for (let j = y; j < n - offset; j++) {
            arr[x][j] = count++;
        }
        // 从上到下填充
        for (let i = x + 1; i < n - offset; i++) {
            arr[i][n - offset - 1] = count++;
        }
        // 从右到左填充
        for (let j = n - offset - 2; j >= y; j--) {
            arr[n - offset - 1][j] = count++;
        }
        // 从下到上填充
        for (let i = n - offset - 2; i > x; i--) {
            arr[i][y] = count++;
        }

        // 更新边界和循环次数
        x++, y++, offset++;
        cishu--;
    }

    // 如果 n 是奇数，填充中心点
    if (n % 2 === 1) {
        arr[x][y] = count;
    }

    return arr;
};
console.log(generateMatrix(n));